<template>
  <a-card :bordered="false" title="商品编辑">
    <a-form :form="form">
      <a-form-item
        label="商品分类"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >{{ spu.cname }}</a-form-item>

      <a-form-item
        label="标题"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-textarea
          v-decorator="[
            'title',
            {initialValue:spu.title,rules: [{ required: true, message: '请输入标题' }]}
          ]"
          placeholder="请输入标题"
        />
      </a-form-item>

      <a-form-item
        label="品牌"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >{{ spu.brandName }}</a-form-item>

      <a-form-item
        label="状态"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-radio-group
          v-decorator="[
            'saleable',
            {initialValue: spu.saleable},
          ]"
        >
          <a-radio :value="true">上线</a-radio>
          <a-radio :value="false">下线</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        label="展示图"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-upload
          v-if="showImgsReset"
          :action="uploadUrl"
          listType="picture"
          :defaultFileList="spu.spuShowImgs"
          class="upload-list-inline"
          @change="spuShowImgsChange"
        >
          <a-button>
            <a-icon type="upload" />upload
          </a-button>
        </a-upload>
      </a-form-item>

      <a-form-item
        label="规格图片"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="{ lg: { span: 20 }, sm: { span: 30 } }"
      >
        <a-card>
          <a-row v-if="spu.saleAttr.length > 0">
            <a-col :span="4" :key="index" v-for="(item,index) in spu.saleAttr[0].options">
              {{ item.name }}:
              <a-upload
                name="file"
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="uploadUrl"
                :data="{id: index}"
                @change="saleAttrImageHandleChange"
              >
                <img width="100" height="100" v-if="item.imgUrl" :src="item.imgUrl" alt="avatar" />
                <div v-else>
                  <a-icon type="plus" />
                  <div class="ant-upload-text">Upload</div>
                </div>
              </a-upload>
            </a-col>
          </a-row>
        </a-card>
      </a-form-item>

      <a-form-item
        label="商品sku"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="{ lg: { span: 20 }, sm: { span: 30 } }"
      >
        <a-table
          :columns="skuColumns"
          :dataSource="spu.skuDatas"
          :rowKey="record => record.attrKey"
          bordered
          :pagination="false"
        >
          <template
            v-for="col in ['price','stock' ,'skuCode']"
            :slot="col"
            slot-scope="text, record, index"
          >
            <div :key="col">
              <a-input v-model="spu.skuDatas[index][col]" style="margin: -5px 0" />
            </div>
          </template>

          <template slot="enable" slot-scope="text, record, index">
            <a-radio-group name="radioGroup" v-model="spu.skuDatas[index]['enable']">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </template>
        </a-table>
      </a-form-item>

      <a-form-item
        label="普通属性"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-col :span="10" :key="index" style="margin: 5px 10px" v-for="(item,index) in spu.attr">
          {{ item.name }} :
          <a-select mode="tags" v-model="item.options" placeholder="属性值" />
        </a-col>
      </a-form-item>

      <a-form-item
        label="商品介绍"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <quill-editor v-model="spu.description" :upload-url="uploadUrl" fileName="file" />
      </a-form-item>

      <a-form-item
        label="包装清单"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-textarea
          v-decorator="[
            'packingList',
            {initialValue:spu.packingList}
          ]"
          placeholder="请输入包装清单"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 12, offset: 15 }">
        <a-button style="margin-right:10px" type="primary" @click="handleCancel">取消</a-button>

        <a-button type="primary" @click="handleSubmit">保存</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>
<script>
import { PageView } from '@/layouts'
import { spuVoGet, spuUpdate } from '@/api/product'
import QuillEditor from '@/components/Editor/QuillEditor'
export default {
  name: 'SpuAdd',
  components: {
    PageView,
    QuillEditor
  },
  data () {
    return {
      skuColumns: commomSkuColumns,
      formItemLayout,
      form: this.$form.createForm(this),
      categoryTreeData: [],
      uploadUrl: process.env.API_BASE_URL + '/base/upload/image',
      spu: {
        cname: '',
        description: '',
        spuShowImgs: [],
        skuDatas: [],
        attr: [],
        brandName: ''
      },
      showImgsReset: false
    }
  },
  methods: {
    handleEdit (record) {
      spuVoGet({ id: record.id }).then(res => {
        const spuData = res.data
        const tmpColumns = []
        spuData.saleAttr.forEach(item => {
          tmpColumns.push({
            title: item.name,
            dataIndex: item.name
          })
        })

        commomSkuColumns.forEach(item => {
          tmpColumns.push(item)
        })
        this.skuColumns = tmpColumns
        const skuDatas = spuData.skus.map(({ id, attrKey, price, stock, enable, image, skuCode, attrMap }) => {
          return {
            id,
            ...attrMap,
            attrKey,
            price,
            stock,
            enable,
            image,
            skuCode
          }
        })

        const showImgList = []
        spuData.showImgList.forEach((item, index) => {
          showImgList.push({
            uid: index,
            name: '展示图',
            status: 'done',
            url: item,
            thumbUrl: item
          })
        })

        this.spu = {
          id: spuData.id,
          cname: spuData.cname,
          title: spuData.title,
          brandName: spuData.brandName,
          saleable: spuData.saleable,
          spuShowImgs: showImgList,
          skuDatas: skuDatas,
          attr: spuData.attr,
          saleAttr: spuData.saleAttr,
          description: spuData.description,
          packingList: spuData.packingList
        }
        this.resetUploadShowImgs()
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const skus = this.spu.skuDatas.map(({ id, attrKey, price, stock, enable, image, skuCode }) => {
            return {
              id,
              price,
              stock,
              enable,
              image,
              skuCode
            }
          })
          console.log('skus', skus)

          const showImgList = this.spu.spuShowImgs.map(item => {
            return item.url
          })
          console.log(values)
          const params = {
            id: this.spu.id,
            title: values.title,
            skus: skus,
            description: this.spu.description,
            showImgList: showImgList,
            attr: this.spu.attr,
            saleAttr: this.spu.saleAttr,
            packingList: values.packingList,
            saleable: values.saleable
          }
          console.log('save spu params', params)

          spuUpdate(params).then(res => {
            if (res.status === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
            } else {
              this.$message.success(res.msg)
            }
          })
        }
      })
    },
    handleCancel: function () {
      this.$emit('cancel')
    },
    spuShowImgsChange (info) {
      console.log('fileList', info)
      const fileList = []
      if (info.file.status === 'done') {
        info.fileList.forEach(item => {
          fileList.push({
            uid: item.uid,
            name: item.name,
            status: 'done',
            url: item.response.data.url,
            thumbUrl: item.response.data.url
          })
          item.thumbUrl = item.response.data.url
        })
        this.spu.spuShowImgs = fileList
      }
      if (info.file.status === 'removed') {
        this.spu.spuShowImgs = info.fileList.filter(item => {
          return item.uid !== info.file.uid
        })
      }
      console.log(this.spu.spuShowImgs)
    },
    saleAttrImageHandleChange (info) {
      if (info.file.status === 'done') {
        const options = [...this.spu.saleAttr[0].options]
        const id = info.file.response.data.id
        const option = options[id]
        option.imgUrl = info.file.response.data.url
        this.spu.saleAttr[0].options = options
      }
    },
    showInput (name) {
      this.spu.saleAttr.forEach(item => {
        if (name === item.name) {
          item.inputVisible = true
          this.$nextTick(function () {
            this.$refs[item.inputRef][0].focus()
          })
        }
      })
    },
    resetUploadShowImgs () {
      this.showImgsReset = false
      this.showImgsReset = true
    }
  },
  mounted () {},
  created () {}
}

const commomSkuColumns = [
  {
    title: '价格',
    dataIndex: 'price',
    width: '20%',
    scopedSlots: { customRender: 'price' }
  },
  {
    title: '库存',
    dataIndex: 'stock',
    width: '20%',
    scopedSlots: { customRender: 'stock' }
  },
  {
    title: '商品编码(可不填)',
    dataIndex: 'skuCode',
    width: '20%',
    scopedSlots: { customRender: 'skuCode' }
  },

  {
    title: '是否上架',
    dataIndex: 'enable',
    width: '15%',
    scopedSlots: { customRender: 'enable' }
  }
]

const formItemLayout = {
  labelCol: { lg: { span: 3 }, sm: { span: 3 } },
  wrapperCol: { lg: { span: 15 }, sm: { span: 30 } }
}
</script>
<style scoped>
/* tile uploaded pictures */
.upload-list-inline >>> .ant-upload-list-item {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline >>> .ant-upload-animate-enter {
  animation-name: uploadAnimateInlineIn;
}
.upload-list-inline >>> .ant-upload-animate-leave {
  animation-name: uploadAnimateInlineOut;
}
</style>
